import { Table, TableProps } from 'antd';
import type { ColumnType } from 'antd/es/table';
import styles from './index.less';

export interface CommonTableProps<T = any>
  extends Omit<TableProps<T>, 'columns'> {
  columns?: ColumnType<T>[];
}

const CommonTable = <T extends Record<string, any> = any>({
  columns = [],
  pagination,
  ...props
}: CommonTableProps<T>) => {
  // 处理columns，为所有列添加默认配置
  const processedColumns = columns.map((column) => ({
    ellipsis: true,
    render: (text: any, record: T, index: number) => {
      // 如果列有自定义render函数，先执行自定义render
      if (column.render) {
        const customResult = column.render(text, record, index);
        // 如果自定义render返回null、undefined或空字符串，显示'-'
        if (
          customResult === null ||
          customResult === undefined ||
          customResult === ''
        ) {
          return '-';
        }
        return customResult;
      }

      // 如果没有自定义render，检查text值
      if (text === null || text === undefined || text === '') {
        return '-';
      }

      return text;
    },
    ...column,
  }));

  return (
    <div className={styles['common-table-container']}>
      <Table<T>
        // size="small"
        {...props}
        bordered
        columns={processedColumns}
        onRow={() => {
          return {
            onClick: (event) => {
              if (document.querySelector('.ant-table-row-custom-selected')) {
                document
                  .querySelector('.ant-table-row-custom-selected')
                  ?.classList.remove('ant-table-row-custom-selected');
              }
              event.currentTarget.classList.add(
                'ant-table-row-custom-selected',
              );
            },
          };
        }}
        pagination={
          pagination === false
            ? false
            : {
                size: 'small',
                position: ['bottomLeft'],
                showQuickJumper: true,
                showSizeChanger: true,
                hideOnSinglePage: false,
                pageSizeOptions: [20, 50, 100, 200],
                showTotal: (total) => `共${total}条数据`,
                ...pagination,
              }
        }
        scroll={{ y: 1 }}
      />
    </div>
  );
};

export default CommonTable;
